#include "main_left_widget.h"
#include "stydatabase.h"
#include "oneperson.h"
#include <QPen>
#include <QSqlQuery>

QDate currentDate; //当天日期
QDate selectedDate;//当前被选中的日期
QTextCharFormat old_farmat;
QDate dateStart;//当前日历页的第一天(有效的，就是不是灰色的)
main_left_widget::main_left_widget()
{
    /* 1.初始化按钮 */
    btn_study = new QPushButton("我的");
    btn_friend = new QPushButton("好友进度");
    btn_news = new QPushButton("学习日报");
    lay_left = new QVBoxLayout;
    calendar = new QCalendarWidget;

    btn_study->setObjectName("btn_study");
    btn_friend->setObjectName("btn_friend");
    btn_news->setObjectName("btn_news");

    btn_study->setAutoFillBackground(true);
    btn_friend->setAutoFillBackground(true);
    btn_news->setAutoFillBackground(true);
    btn_pixmap = QPixmap(":/img/img/btn_back.png");
    btn_study->setFlat(true);
    btn_friend->setFlat(true);
    btn_news->setFlat(true);
    btn_study->setToolTip(tr("查看我的学习情况"));
    btn_friend->setToolTip(tr("查看好友学习进度"));
    btn_news->setToolTip(tr("查看学习日报"));
    /* 2.设置日历基本属性 */
    init_calendar(calendar);

    /* 3.添加到widget */
    lay_left->addWidget(calendar);
    lay_left->addLayout(toolLayout);
    lay_left->addWidget(btn_study);
    lay_left->addWidget(btn_friend);
    lay_left->addWidget(btn_news);
    lay_left->addStretch();

    this->setLayout(lay_left);
    lay_left->setSpacing(0);
    lay_left->setMargin(0);             //设置外边距

    this->setContentsMargins(0,0,0,0);
    this->setWindowOpacity(0.8);
    connect(this->btn_news,SIGNAL(clicked(bool)),this,SLOT(newsBtnClicked()));
    connect(this->btn_friend,SIGNAL(clicked(bool)),this,SLOT(friendBtnClicked()));
    connect(this->btn_study,SIGNAL(clicked(bool)),this,SLOT(studyBtnClicked()));
    studyBtnClicked();
}
/**
 * @brief main_left_widget::paintEvent
 *      为了使用qss,必须重载这个函数
 * @param event
 */
void main_left_widget::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

/**
 * @brief main_left_widget::dumpStructure
 *        打印复杂控件树形组成结构
 * @param obj 控件名
 * @param spaceCount 空格数
 */
void main_left_widget::dumpStructure(const QObject *obj, int spaceCount)
{
    qDebug() << QString("%1%2 : %3")
                .arg("", spaceCount)
                .arg(obj->metaObject()->className())
                .arg(obj->objectName());

    QObjectList list = obj->children();

    foreach (QObject * child, list) {
        dumpStructure(child, spaceCount + 4);
    }
}
/**
 * @brief main_left_widget::init_calendar
 *          初始化日历界面，包括一些工具按钮
 * @param calendar
 */
void main_left_widget::init_calendar(QCalendarWidget *calendar)
{
    calendar->setMinimumDate(QDate(1900,1,1));      //设置最小日期
    calendar->setMaximumDate(QDate(3000,1,1));      //最大日期
    //calendar->setGridVisible(true);                 //画上格子
    currentDate = QDate::currentDate();
    old_farmat =calendar->dateTextFormat(currentDate);
    QTextCharFormat format;
    format.setBackground(Qt::red);                  //设置格式
    calendar->setDateTextFormat(currentDate, format);   //生效配置
    whenSelectionChanged();
    reformatCalendarPage();
    connect(calendar, SIGNAL(currentPageChanged(int,int)),this, SLOT(reformatCalendarPage()));//当前页改变就重新设置一下页面格式
    connect(calendar, SIGNAL(selectionChanged()),this,SLOT(whenSelectionChanged()));

    m_ReturnToday = new DisplayButton;
    m_ReturnToday->setIcon(QIcon(":/img/img/go_back_today.png"));
    m_ReturnToday->setToolTip(tr("go back today")); //回到今天
    connect(m_ReturnToday, SIGNAL(clicked()),this, SLOT(ReturnToday()));

    m_ShowClock = new DisplayButton;
    m_ShowClock->setIcon(QIcon(":/img/img/clock.png"));
    m_ShowClock->setToolTip(tr("显示时钟"));           //时钟
    connect(m_ShowClock, SIGNAL(clicked()),this, SLOT(ShowClockButtonClicked()));
    connect(btn_study,SIGNAL(clicked()),this,SLOT(studyBtnClicked()));

    m_ConfigureButton = new DisplayButton;
    m_ConfigureButton->setText("display");
    m_ConfigureButton->setIcon(QIcon(":/img/img/configure.png"));
    m_ConfigureButton->setToolTip(tr("设置")); //显示设置
    connect(m_ConfigureButton, SIGNAL(clicked()),
            this, SLOT(AboutButtonClicked()));

    m_AboutButton = new DisplayButton;
    m_AboutButton->setIcon(QIcon(":/img/img/about.png"));
    m_AboutButton->setToolTip(tr("关于软件"));     //关于产品
    connect(m_AboutButton, SIGNAL(clicked()),this, SLOT(AboutButtonClicked()));

    toolLayout = new QHBoxLayout;
    toolLayout->addStretch();
    toolLayout->addWidget(m_ReturnToday);
    toolLayout->addWidget(m_ShowClock);
    toolLayout->addWidget(m_ConfigureButton);
    toolLayout->addWidget(m_AboutButton);
    toolLayout->addStretch();

}

void main_left_widget::getEverydayData(QDate &dateStart, QDate &dateEnd, styData &stydata1)
{
    stydata1.in_factData.resize(31);
    stydata1.actual_Data.resize(31);
    stydata1.balanceData.resize(31);
    stydata1.overfulData.resize(31);
    for(int i=0;i<31;i++){
        stydata1.in_factData[i]=0;
        stydata1.actual_Data[i]=0;
        stydata1.balanceData[i]=0;
        stydata1.overfulData[i]=0;
    }
//    QSqlQuery query;
//    QString queryString = QString("select PIdent from Pens where POwner = \"%1\"").arg(stydata1.friends.UName);
//    query.prepare(queryString);
//    query.exec();
//    QString penName="pen0001";
//    if(query.next()){
//        penName = query.value(0).toString();
//    }
//    qDebug()<<"penName = "<<penName;
//    int i=0;
//    QDate datastart = dateStart;
//    qDebug()<<datastart<<dateEnd;
//    while(datastart < dateEnd){
//        queryString = QString("select PStyTime from %1 where PDay = \"%2-%3-%4\"").arg(penName).arg(datastart.year()).arg(datastart.month()).arg(datastart.day());
//        query.prepare(queryString);
//        query.exec();
//        while(query.next()){
//            //qDebug()<<"query.value(0).toULongLong():"<<query.value(0).toULongLong();
//            stydata1.actual_Data[i]+=bitCount(query.value(0).toULongLong());
//            //stydata1.in_factData[i]+=bitCount(query.value(0).toULongLong());
//        }
//        stydata1.in_factData[i]=stydata1.actual_Data[i];
//        double targetTime = stydata1.friends.UTgDayTime*60;
//        if(stydata1.friends.UTgDayTime*60 > stydata1.in_factData[i]){//如果目标没完成
//            stydata1.balanceData[i] = targetTime - stydata1.in_factData[i];
//        }else{
//            stydata1.overfulData[i] = stydata1.in_factData[i] - targetTime;
//            stydata1.in_factData[i] = targetTime;
//        }
//        //qDebug()<<"in_factData["<<i<<"]:"<<stydata1.in_factData[i];
//        i++;
//        datastart = datastart.addDays(1);
//    }
    qDebug()<<"file:"<<__FILE__<<",line: "<<__LINE__<<",等调试完要记得改回来";
}

void main_left_widget::getEveryoneData()
{
    qDebug()<<"g_data.size():"<<g_data.size();
    for(int i=0;i<g_data.size();i++){
        getEverydayData(dateStart,dateEnd,g_data[i]);
    }
}

int main_left_widget::bitCount(qulonglong number)
{
    unsigned int c =0 ;
    for (c =0; number; ++c){
        number &= (number -1) ; // 清除最低位的1
    }
    return c;
}

void main_left_widget::ReturnToday()
{
    calendar->setSelectedDate(currentDate);
}

void main_left_widget::AboutButtonClicked()
{
    QMessageBox::about(this, tr("毕业设计"),
             tr("<h1> 基于物联网的学习系统设计</h1>"
             "通信1502班 贺佐强 201554080231"
             "<p><h4>Release 1.0</h4>"
             "<p>Copyright &copy; 2018-2019 Inc. & llongint "
             "All rights reserved."
             "<p>版权所有 © 2018-2019 Inc. & llongint。 保留所有权利。"
             "<p>警告：本计算机程序是作者的毕业设计程序的一部分，未经授权擅自复制或传播本程序"
             "的部分或全部，可能受到严厉的民事及刑事制裁，并将在法律许可的范围内受到最大"
             "可能的起诉。"
                ));
}
/**
 * @brief main_left_widget::reformatCalendarPage
 *      当前日期页发生改变
 */
void main_left_widget::reformatCalendarPage()
{
    QDate firstDay(calendar->yearShown()-1, calendar->monthShown(), 1);//当前日历页的第一天
    firstDay=firstDay.addDays(358);
    //if(hzq)qDebug()<<"first day:"<<firstDay<<endl;

    QTextCharFormat dayFormat_light;    //日期显示样式_浅色
    QTextCharFormat dayFormat_deep;     //日期显示样式_深色
    dayFormat_light.setForeground(QColor(230, 230, 230));
    dayFormat_light.setFont(QFont("",0,30));
    dayFormat_deep.setForeground(QColor(0, 0, 0));
    dayFormat_deep.setFont(QFont("Helvetica [Cronyx]",12,QFont::ExtraBold));

    /* 不是这一个月的日期设置得暗一点 */
    while(firstDay.day()!=1){
        calendar->setDateTextFormat(firstDay,dayFormat_light);
        firstDay=firstDay.addDays(1);
    }
    dateStart = firstDay;
    do{
        calendar->setDateTextFormat(firstDay,dayFormat_deep);
        firstDay=firstDay.addDays(1);
    }while(firstDay.day()!=1);
    dateEnd = firstDay;
    for(int i=0;i<10;i++){
        calendar->setDateTextFormat(firstDay,dayFormat_light);
        firstDay=firstDay.addDays(1);
    }
    calendar->setMaximumHeight(290);

    dayFormat_deep.setFontOverline(true);
    dayFormat_deep.setFontUnderline(true);
    QSqlQuery query;
    QString queryString = QString("select PDay from %1 where PDay between \"%2-%3-%4\" and \"%5-%6-%7\"").arg(g_data[0].friends.penName).arg(dateStart.year()).arg(dateStart.month()).arg(dateStart.day()).arg(dateEnd.year()).arg(dateEnd.month()).arg(dateEnd.day());
    query.prepare(queryString);
    query.exec();
    while(query.next()){
        calendar->setDateTextFormat(query.value(0).toDate(),dayFormat_deep);
    }
    if(g_data.size()>0){
        getEveryoneData();
    }
}

void main_left_widget::whenSelectionChanged()
{
    if(hzq)qDebug()<<"whenSelectionChanged";
    currentDate = QDate::currentDate();
    QTextCharFormat dayFormat_current;    //日期显示样式_当天日期
    QTextCharFormat dayFormat_selected;   //日期显示样式_被选中的日期

    /* 1.当前日期样式 */
    dayFormat_current.setForeground(QColor(0, 0, 0));
    dayFormat_current.setFont(QFont("",0,30));
    dayFormat_current.setFontOverline(true);
    dayFormat_current.setFontUnderline(true);
    dayFormat_current.setToolTip(QString("this is a test string"));
    dayFormat_current.setBackground(QColor(216, 30, 6));//红色


    calendar->setDateTextFormat(currentDate,dayFormat_current);
    calendar->setDateTextFormat(selectedDate,old_farmat);

    /* 2.被选中日期样式 */
    selectedDate = calendar->selectedDate();
    old_farmat =calendar->dateTextFormat(selectedDate);//先保存这个样式
    dayFormat_selected.setForeground(QColor(0, 0, 0));//黑色
    dayFormat_selected.setFont(QFont("Helvetica [Cronyx]",12,QFont::ExtraBold));
    //dayFormat_selected.setFontUnderline(true);
    dayFormat_selected.setUnderlineColor(QColor(235, 97, 166));
    QPen pen=calendar->dateTextFormat(currentDate).textOutline();
    pen.setColor(QColor(233, 55, 55));
    pen.setBrush(Qt::green);
    dayFormat_selected.setTextOutline(pen);
    calendar->setDateTextFormat(selectedDate,dayFormat_selected);

    emit sigSelectionChanged();
}

/**
 * @brief main_left_widget::ShowClockButtonClicked
 *       显示始终按钮被按下
 */
void main_left_widget::ShowClockButtonClicked()
{
    emit sigClockButtonClicked();
}
void main_left_widget::studyBtnClicked()
{
   this->setStyleSheet("QPushButton#btn_friend,#btn_news{\
                                  background-color: rgb(255,255,255);\
                                  color: rgb(163, 163, 163);\
                                  min-width: 160px;\
                                  min-height: 70px;\
                                  background-repeat: repeat;\
                                  font-size: 24px;\
                        }\
                        QPushButton#btn_study{\
                              background-image: url(:/img/img/btn_back.png); \
                        }\
                        QPushButton#btn_study:hover,#btn_friend:hover,#btn_news:hover {\
                              color: rgb(163,163,163);\
                              background-color: rgb(230, 230, 230);\
                          }");

    emit sigBtnStudyClicked();
}
void main_left_widget::friendBtnClicked()
{
   this->setStyleSheet("QPushButton#btn_study,#btn_news{\
                                  background-color: rgb(255,255,255);\
                                  color: rgb(163, 163, 163);\
                        }\
                        QPushButton#btn_friend{\
                              background-image: url(:/img/img/btn_back.png); \
                        }\
                        QPushButton#btn_study:hover,#btn_friend:hover,#btn_news:hover {\
                              color: rgb(163,163,163);\
                              background-color: rgb(230, 230, 230);\
                          }");
    emit sigBtnFriendClicked();
}
void main_left_widget::newsBtnClicked()
{
   this->setStyleSheet("QPushButton#btn_study,#btn_friend{\
                                  background-color: rgb(255,255,255);\
                                  color: rgb(163, 163, 163);\
                        }\
                        QPushButton#btn_news{\
                              background-image: url(:/img/img/btn_back.png); \
                        }\
                        QPushButton#btn_study:hover,#btn_friend:hover,#btn_news:hover {\
                              color: rgb(163,163,163);\
                              background-color: rgb(230, 230, 230);\
                        }");
    emit sigBtnNewsClicked();
}

